package org.zjx.swing.view;

import com.sun.jna.platform.win32.User32;
import com.sun.jna.platform.win32.WinDef;
import org.zjx.swing.bean.ColorRecord;
import org.zjx.swing.bean.FontFilePath;
import org.zjx.entity.LiterateSubScreenBean;
import org.zjx.swing.bean.WordBean;
import org.zjx.swing.controller.LiterateController;
import org.zjx.swing.font.FontUtil;
import org.zjx.swing.model.LiterateModel;
import org.zjx.swing.util.ColorItemRenderer;
import org.zjx.swing.util.ImageDisplayPanel;
import org.zjx.swing.util.PathItemRenderer;
import org.zjx.util.ImageUtil;
import org.zjx.util.NumberLengthLimitedDmt;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.atomic.AtomicReference;

import static org.zjx.swing.view.PropView.getHwndS;

public class LiterateView extends JFrame {
    private JPanel imagePanel;
    private JLabel thumbnailLabel;
    private JLabel imageLabel;
    private JLabel pathValue;
    private JLabel sizeValue;
    private JLabel timeValue;
    private JTextField[] captureFields = new JTextField[4];
    private JComboBox<String> captureComboBox;
    private JButton captureConfirmButton;
    private JTextField fontHeight;

    private JButton addFontFilePathButton;
    private JButton deleteFontFileButton;

    private JButton addColorListButton;
    private JButton deleteColorListButton;

    private DefaultListModel<FontFilePath> pathListModel = new DefaultListModel<>();
    private JList<FontFilePath> pathList = new JList<>(pathListModel);

    // 颜色列表模型
    private DefaultListModel<ColorRecord> colorListModel = new DefaultListModel<>();
    private JList<ColorRecord> colorList = new JList<>(colorListModel);

    private JTextArea displayTextArea;
    private JButton recognizeButton;
    private JButton taskBoxButton;
    private ImageDisplayPanel imageDisplayPanel;

    private JTextArea identifyArea;
    private JTextField inputField;

    private JButton identifyButton;
    private JButton previousButton;
    private JButton nextButton;
    private JButton mergeButton;
    private JButton okButton;
    private Robot robot;
    private BufferedImage screen;
    private JButton captureButton;


    public LiterateView() {
        setTitle("字库界面");
        setSize(1000, 600);
        setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
        setLocationRelativeTo(null);

        JSplitPane splitPane = new JSplitPane(JSplitPane.HORIZONTAL_SPLIT);
        splitPane.setDividerLocation(0.25); // 设置左面板占 25% 的宽度
        splitPane.setResizeWeight(0.25); // 可选：设置调整大小时的权重

        JPanel leftPanel = createLeftPanel();
        splitPane.setLeftComponent(leftPanel);
        leftPanel.setVisible(true);

        JPanel rightPanel = createRightPanel();
        splitPane.setRightComponent(rightPanel);

        add(splitPane);
    }

    public JPanel createLeftPanel(){
        JPanel leftPanel = new JPanel();
        leftPanel.setLayout(new BorderLayout());

        JPanel topPanel = new JPanel();
        topPanel.setLayout(new BorderLayout());

        imagePanel = new JPanel(new BorderLayout());

        thumbnailLabel = new JLabel();
        thumbnailLabel.setHorizontalAlignment(SwingConstants.CENTER);
        thumbnailLabel.setVerticalAlignment(SwingConstants.CENTER);
        thumbnailLabel.setBorder(BorderFactory.createLineBorder(Color.BLACK));
        thumbnailLabel.setPreferredSize(new Dimension(150, 150));
        thumbnailLabel.setCursor(new Cursor(Cursor.HAND_CURSOR));

        imagePanel.add(thumbnailLabel, BorderLayout.NORTH);
        topPanel.add(imagePanel, BorderLayout.NORTH);

        JPanel attributesPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        String[] labels = {"路径:", "大小:", "时间:"};
        JLabel[] labelComponents = new JLabel[labels.length];
        JLabel[] valueComponents = {new JLabel(), new JLabel(), new JLabel()};
        pathValue = valueComponents[0];
        sizeValue = valueComponents[1];
        timeValue = valueComponents[2];

        JLabel totalCaptureLabel = new JLabel("截取范围:");
        gbc.gridx = 0;
        gbc.gridy = labels.length;
        attributesPanel.add(totalCaptureLabel, gbc);

        // 添加文本框和下拉选择框的面板
        JPanel captureFieldsPanel = new JPanel(new GridLayout(1, 6, 5, 5)); // 调整为5列以容纳下拉选择框

        // 添加四个文本框
        for (int i = 0; i < 4; i++) {
            captureFields[i] = new JTextField();
            captureFields[i].setColumns(3);
            captureFields[i].setDocument(new NumberLengthLimitedDmt(3));
            captureFieldsPanel.add(captureFields[i]);
        }

        // 添加下拉选择框
        captureComboBox  = new JComboBox<>();
        captureFieldsPanel.add(captureComboBox);

        gbc.gridx = 1;
        gbc.gridy = labels.length;
        attributesPanel.add(captureFieldsPanel, gbc);

        // 假设缩小到 12 号字体，可按需调整
        Font buttonFont = new Font("宋体", Font.PLAIN, 20);

        captureConfirmButton = new JButton("截取");
        captureConfirmButton.setFont(buttonFont); 

        // 缩短截取按钮宽度，调整跨越列数
        GridBagConstraints gbcCaptureConfirm = new GridBagConstraints();
        gbcCaptureConfirm.gridx = 1;
        gbcCaptureConfirm.gridy = labels.length + 1;
        gbcCaptureConfirm.gridwidth = 3; 
        gbcCaptureConfirm.insets = new Insets(0, 5, 0, 0); // 设置左边间距为 5px
        attributesPanel.add(captureConfirmButton, gbcCaptureConfirm);

        captureButton = new JButton("游戏截图****");
        captureButton.setFont(buttonFont); 

        GridBagConstraints gbcLeftButton = new GridBagConstraints();
        gbcLeftButton.gridx = 0; 
        gbcLeftButton.gridy = labels.length + 1;
        gbcLeftButton.insets = new Insets(0, 0, 0, 0); // 设置右边间距为 5px
        attributesPanel.add(captureButton, gbcLeftButton);

        taskBoxButton = new JButton("任务框");
        taskBoxButton.setFont(buttonFont);
        GridBagConstraints gbcTaskButton = new GridBagConstraints();
        gbcTaskButton.gridx = 0;
        gbcTaskButton.gridy = labels.length+2;
        gbcTaskButton.insets = new Insets(0, 0, 0, 5); // 设置右边间距为 5px
        attributesPanel.add(taskBoxButton, gbcTaskButton);

        // 添加任务详情按钮
        JButton taskDetailButton = new JButton("任务详情");
        taskDetailButton.setFont(buttonFont);
        GridBagConstraints gbcTaskDetailButton = new GridBagConstraints();
        gbcTaskDetailButton.gridx = 1;
        gbcTaskDetailButton.gridy = labels.length + 2;
        gbcTaskDetailButton.insets = new Insets(0, 0, 0, 5);
        attributesPanel.add(taskDetailButton, gbcTaskDetailButton);

        taskDetailButton.addActionListener(e -> {
            WinDef.RECT rect = getBoundsNow(getGameScreen());
            if (rect != null) {
                // 将 rect 的值依次放入 4 个输入框
                captureFields[0].setText((String.valueOf(rect.left)));
                captureFields[1].setText(String.valueOf(rect.top));
                captureFields[2].setText((String.valueOf(rect.right)));
                captureFields[3].setText(String.valueOf(rect.bottom));
            }
        });

        taskBoxButton.addActionListener(e -> {
            WinDef.RECT rect = getBoundsNow2(getGameScreen());
            if (rect != null) {
                // 将 rect 的值依次放入 4 个输入框
                captureFields[0].setText(String.valueOf(rect.left));
                captureFields[1].setText(String.valueOf(rect.top));
                captureFields[2].setText(String.valueOf(rect.right));
                captureFields[3].setText(String.valueOf(rect.bottom));
            }
        });

        for (int i = 0; i < labels.length; i++) {
            labelComponents[i] = new JLabel(labels[i]);
            gbc.gridx = 0;
            gbc.gridy = i;
            attributesPanel.add(labelComponents[i], gbc);

            gbc.gridx = 1;
            attributesPanel.add(valueComponents[i], gbc);
        }

        topPanel.add(attributesPanel, BorderLayout.CENTER);
        leftPanel.add(topPanel, BorderLayout.NORTH);

        JPanel imageContainer = new JPanel(new BorderLayout());
        imageContainer.setBackground(Color.GRAY);
        imageLabel = new JLabel();
        imageLabel.setHorizontalAlignment(SwingConstants.CENTER);
        imageLabel.setVerticalAlignment(SwingConstants.CENTER);
        imageContainer.add(imageLabel, BorderLayout.CENTER);

        JScrollPane scrollPane = new JScrollPane(imageContainer);
        leftPanel.add(scrollPane, BorderLayout.CENTER);


        return leftPanel;
    }

    // 定义字体大小为 30 的字体
    Font rightButtonFont = new Font("宋体", Font.PLAIN, 25);

    public BufferedImage getGameScreen() {
        List<WinDef.HWND> hwnds = getHwndS("WSGAME", null);
        if (hwnds.isEmpty()) return null;
        if (robot == null) {
            try {
                robot = new Robot();
            } catch (AWTException e) {
                throw new RuntimeException(e);
            }
        }

        WinDef.RECT rect = new WinDef.RECT();
        User32.INSTANCE.GetWindowRect(hwnds.get(0), rect);
        rect.top = rect.top + 31;
        rect.left = rect.left + 8;
        rect.right = rect.right - 8;
        rect.bottom = rect.bottom - 8;
        screen = robot.createScreenCapture(rect.toRectangle());
        return screen;
    }

    public  BufferedImage  reference() {
        String image = "iVBORw0KGgoAAAANSUhEUgAAAD4AAAAQCAYAAABOZ8wCAAADYklEQVR4XpWVWW/aQBDH/dAcHMZgDIaQOARoSCg51EhtiFKURImElDZK1Zd8hD5W6vfXdP9rBsbD4tCRfrJ37p314T1Ph/Q0GdDkIqG/r6cL2s2Ajg6aNOy1qJe07P3s24jubz7Z6+zuwsQh1nA7ssym40wO2J7vP1vfh6+Dpb+phzX04OXpKhP38ng554qepybvrckzBSN7/Tmb0MvDWcrcd9VvRMeHUYbuXs3SbvjkPXwZ0CCJzKJii0LSjVep0woXeg1imOPDhoVtnGMdg4OQzk8TOj9JaHzcoVE/zsTxOo/xxw6Nh/vGt02j3rL2JrTqZfL6BxHtxTULlOualoI1BhOHZYrrwHf6ucQWjnwz0IBahqbJ0ayVMrWRMy8XbOjX1p/3kOcvhfN7KKwbdyWRQ7DNo2kT16gWVzatfWVeGxtVKDag9jof11rqGmZYEu2XB/y9KChSPShkkmpYD9+oWjIUbdNovjFvXsbqPHK9iMXQxElrWaeHcJ6Uku0Lh8DDzONoP6Jht0EeNy4bRFMAyaS+boeUElYK1s4+GilSn8a7Y7WvXksd59H2TfH4RjaJhDV/18I2XEO/kIHtEpknTwcwdJw6csk6Ok4L9yL7+1+xG4e4CssGtA64CmsfnUf6LR/X9DvBer6+B05d6yR5eRYnLh03EfhVy6snrnOtIyjvUFDaWYnhuPcEPhgYXjlG11133zG/aA+P9aYfNwmaBpV585sKfBEDeOPa7kLbMHRsVr6S2k/HyLWH4n5xO2PgZBWlx1qCOPbR6KI6D2K5rrbrfvQ9qJonhlnnw+s4XP7uWOc1zO9AF8I6NBuXJ8J6F+XCVmYTsgFskptz5SkXlgNgO/LpPFKw5ifOVVP3HZsPaEv9vbyzbkj9dpBxLO1uZabJejTkAv7uBrYtro3xwFx1XLm0DQNFbm3jp1HqB3sBDZMajbvRQu/dn7XpethcSSBx6bFZxuUHPZ+ctsvXxWWX9/oq4Y0z8qmTMRfdJt2MOvTjur+weX9eL+nttruSPE9gL+1+WKBj04FkbdLu48Tn6Fo6l7azQF+vmG+ReVok2h/rx8sO/Zokdp9vdyf0e3ZiNv49vZGFNiEyRRmpj6uFDDquE5UzaLv21TrJfr1IR7FPSXOJ9gGv190M2PM/uhtY7sP0u94AAAAASUVORK5CYII=";
        try {
            return ImageUtil.stringToBufferedImage(image);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public  WinDef.RECT getBoundsNow(BufferedImage screen) {
        try {
            List<Point> points = ImageUtil.matchTemplate(screen, reference());
            if (points.isEmpty()) return null;
            WinDef.RECT rect = new WinDef.RECT();
            rect.left = points.get(0).x +43;
            rect.top = points.get(0).y +52;
            rect.right = points.get(0).x +198;
            rect.bottom = points.get(0).y +307;
            return rect;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    public  WinDef.RECT getBoundsNow2(BufferedImage screen) {
        try {
            List<Point> points = ImageUtil.matchTemplate(screen, reference());
            if (points.isEmpty()) return null;
            WinDef.RECT rect = new WinDef.RECT();
            rect.left = points.get(0).x -147;
            rect.top = points.get(0).y +52;
            rect.right = points.get(0).x +8;
            rect.bottom = points.get(0).y +307;
            return rect;
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public JPanel createRightPanel(){
        JPanel rightPanel = new JPanel(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();

        gbc.fill = GridBagConstraints.BOTH;
        gbc.weightx = 1.0;

        // 第一部分：路径展示和选择（占10%）
        JPanel pathSelectionPanel = new JPanel(new BorderLayout());
        pathSelectionPanel.setBorder(BorderFactory.createTitledBorder("路径选择"));

        // 自定义列表项渲染器以添加复选框
        pathList.setCellRenderer(new PathItemRenderer());
        pathList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
        pathListModel = new DefaultListModel<>(); // 初始化模型
        pathList.setModel(pathListModel);

        // 设置固定高度（可根据需要调整）
        pathList.setFixedCellHeight(20); // 假设每行高度为20像素

        JScrollPane scrollPane = new JScrollPane(pathList);
        scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_AS_NEEDED);

        // 创建一个顶部面板来放置滚动列表
        JPanel topPanel = new JPanel(new BorderLayout());
        topPanel.add(scrollPane, BorderLayout.CENTER);

        // 创建一个右侧按钮面板
        JPanel rightButtonPanel = new JPanel();
        rightButtonPanel.setLayout(new BoxLayout(rightButtonPanel, BoxLayout.Y_AXIS)); // 垂直布局

        addFontFilePathButton = new JButton("添加路径");
        addFontFilePathButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        deleteFontFileButton = new JButton("删除");
        deleteFontFileButton.setFont(rightButtonFont); // 设置按钮字体大小为 30

        rightButtonPanel.add(addFontFilePathButton);
        rightButtonPanel.add(Box.createVerticalStrut(5)); // 添加间距
        rightButtonPanel.add(deleteFontFileButton);
        rightButtonPanel.add(Box.createVerticalGlue()); // 添加弹性空间，使按钮靠上对齐

        // 将滚动列表和右侧按钮面板组合在一起
        JPanel pathContentPanel = new JPanel(new BorderLayout());
        pathContentPanel.add(topPanel, BorderLayout.CENTER);
        pathContentPanel.add(rightButtonPanel, BorderLayout.EAST);

        pathSelectionPanel.add(pathContentPanel, BorderLayout.CENTER);

        gbc.weighty = 0.20; // 10% 高度
        gbc.gridx = 0;
        gbc.gridy = 0;
        rightPanel.add(pathSelectionPanel, gbc);

        // 第二部分：颜色选择（占10%）
        JPanel colorPanel = new JPanel(new BorderLayout());
        colorPanel.setBorder(BorderFactory.createTitledBorder("颜色选择（多选是shift+鼠标左键）"));
        gbc.weighty = 0.20;
        gbc.gridy = 1;

        colorList.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);

        JScrollPane colorScrollPane = new JScrollPane(colorList);

        // 添加颜色按钮
        addColorListButton = new JButton("添加颜色");
        addColorListButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        deleteColorListButton = new JButton("删除");
        deleteColorListButton.setFont(rightButtonFont); // 设置按钮字体大小为 30

        // 按钮面板布局
        JPanel colorButtonPanel = new JPanel();
        colorButtonPanel.setLayout(new BoxLayout(colorButtonPanel, BoxLayout.Y_AXIS));
        colorButtonPanel.add(addColorListButton);
        colorButtonPanel.add(Box.createVerticalStrut(5)); // 添加间距
        colorButtonPanel.add(deleteColorListButton);
        colorButtonPanel.add(Box.createVerticalGlue());

        // 组合内容
        JPanel colorContentPanel = new JPanel(new BorderLayout());
        colorContentPanel.add(colorScrollPane, BorderLayout.CENTER);
        colorContentPanel.add(colorButtonPanel, BorderLayout.EAST);
        colorPanel.add(colorContentPanel, BorderLayout.CENTER);

        rightPanel.add(colorPanel, gbc);

        // 第三部分（占40%）
        JPanel thirdPanel = new JPanel(new BorderLayout());
        thirdPanel.setBorder(BorderFactory.createTitledBorder("自动识别"));
        gbc.weighty = 3; // 40% 高度
        gbc.gridy = 2;

        // 创建展示框
        JPanel displayPanel = new JPanel(new BorderLayout());
        // 使用 JTextArea 替代 JLabel 以支持多行文本
        displayTextArea = new JTextArea();
        displayTextArea.setLineWrap(true); // 启用自动换行
//        displayTextArea.setWrapStyleWord(true); // 单词边界换行
        displayTextArea.setEditable(false); // 设置为不可编辑
        displayTextArea.setBackground(Color.WHITE); // 设置背景颜色为白色
        displayTextArea.setFont(new Font("宋体", Font.PLAIN, 20));
        // 将 JTextArea 添加到 JScrollPane 中以支持滚动
        JScrollPane scrollPanes = new JScrollPane(displayTextArea);
        displayPanel.add(scrollPanes, BorderLayout.CENTER);
        // 创建“识别”按钮
        recognizeButton = new JButton("识别");
        // 将按钮添加到展示框的下方
        JPanel buttonPanel = new JPanel();
        buttonPanel.add(recognizeButton);

        // 创建一个面板
        JPanel fontHeightPanel = new JPanel();
        // 创建标签
        JLabel heightLabel = new JLabel("字高");
        // 创建数字输入框，设置默认值为14
        fontHeight = new JTextField("14", 3);
        // 将标签和输入框添加到面板
        fontHeightPanel.add(heightLabel);
        fontHeightPanel.add(fontHeight);
        buttonPanel.add(fontHeightPanel);


        // 将展示框和按钮组合在一起
        JPanel thirdContentPanel = new JPanel(new BorderLayout());
        thirdContentPanel.add(displayPanel, BorderLayout.CENTER);
        thirdContentPanel.add(buttonPanel, BorderLayout.SOUTH); // 将按钮面板放在南部

        thirdPanel.add(thirdContentPanel, BorderLayout.CENTER);

        rightPanel.add(thirdPanel, gbc);

        // 第四部分（占40%）
        JPanel fourthPanel = new JPanel(new BorderLayout());
        fourthPanel.setBorder(BorderFactory.createTitledBorder("手动识别"));
        gbc.weighty = 0.4; // 40% 高度
        gbc.gridy = 3;

        // 主面板使用GridBagLayout实现复杂布局
        JPanel fourthContentPanel = new JPanel(new GridBagLayout());
        GridBagConstraints panelGBC = new GridBagConstraints();
        panelGBC.fill = GridBagConstraints.BOTH;
        panelGBC.weightx = 1.0;
        panelGBC.weighty = 1.0;

        // 左侧大展示框（缩短高度）
        imageDisplayPanel = new ImageDisplayPanel();
        // 创建 JScrollPane 包裹 ImageDisplayPanel
//        JScrollPane scrollPane = new JScrollPane(imagePanel);
//        scrollPane.setPreferredSize(new Dimension(1200, 200));  // 设置 JScrollPane 的固定尺寸

//        JPanel largeDisplayPanel = new JPanel(new BorderLayout());
//        largeDisplayTextArea = new JTextArea();
//        largeDisplayTextArea.setLineWrap(false);
//        largeDisplayTextArea.setEditable(false);
//        largeDisplayTextArea.setBackground(Color.WHITE);

        JScrollPane largeScrollPane = new JScrollPane(imageDisplayPanel);
        largeScrollPane.setPreferredSize(new Dimension(1200, 200)); // 设置固定尺寸

        // 修改右侧容器为GridBagLayout
        JPanel rightPanels = new JPanel(new GridBagLayout()); // 替换GridLayout
        GridBagConstraints rightGBC = new GridBagConstraints();
        rightGBC.fill = GridBagConstraints.BOTH;
        rightGBC.weightx = 1.0;
        rightGBC.weighty = 1.0;

        // 添加小展示框1（固定高度）
        rightGBC.gridy = 0;
        rightGBC.weighty = 0.3; // 占据30%高度

        JPanel identifyPanel = new JPanel(new BorderLayout());

        JLabel label = new JLabel("现在:");
        label.setFont(new Font("宋体", Font.PLAIN, 25)); // 设置标签字体大小为30
        label.setPreferredSize(new Dimension(100, 0)); // 设置固定宽度为120, 高度为0，自动适应
        label.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0)); // 设置左边间隔10个像素点
        identifyPanel.add(label, BorderLayout.WEST);

        // 原始文本展示面板
        identifyArea = new JTextArea();
        identifyArea.setLineWrap(true);
        identifyArea.setEditable(false);
        identifyArea.setBackground(Color.LIGHT_GRAY);
        identifyArea.setFont(new Font("宋体", Font.PLAIN, 30)); // 设置文本区域字体大小为30
        identifyPanel.add(new JScrollPane(identifyArea),BorderLayout.CENTER);

        rightPanels.add(identifyPanel, rightGBC);

        // 添加输入框（剩余高度）
        rightGBC.gridy = 2;
        rightGBC.weighty = 0.5; // 占据40%高度

        JPanel inputPanel = new JPanel(new BorderLayout());

        JLabel updateLabel = new JLabel("修改:");
        updateLabel.setFont(new Font("宋体", Font.PLAIN, 25)); // 设置标签字体大小为30
        updateLabel.setPreferredSize(new Dimension(100, 0)); // 设置固定宽度为120, 高度为0，自动适应
        updateLabel.setBorder(BorderFactory.createEmptyBorder(0, 30, 0, 0)); // 设置左边间隔10个像素点
        inputPanel.add(updateLabel, BorderLayout.WEST);

        inputField = new JTextField();
        inputField.setFont(new Font("宋体", Font.PLAIN, 30)); // 设置输入框字体大小为30
        inputPanel.add(inputField,BorderLayout.CENTER);

        rightPanels.add(inputPanel, rightGBC);

        // 底部按钮面板
        JPanel buttonPanel2 = new JPanel(new FlowLayout(FlowLayout.CENTER));
        identifyButton = new JButton("识别");
        identifyButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        previousButton = new JButton("上一个");
        previousButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        nextButton = new JButton("下一个");
        nextButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        mergeButton = new JButton("合并");
        mergeButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        okButton = new JButton("确认");
        okButton.setFont(rightButtonFont); // 设置按钮字体大小为 30
        buttonPanel2.add(identifyButton);
        buttonPanel2.add(previousButton);
        buttonPanel2.add(nextButton);
        buttonPanel2.add(mergeButton);
        buttonPanel2.add(okButton);


        // 布局约束设置
        panelGBC.gridx = 0;
        panelGBC.gridy = 0;
        panelGBC.gridheight = 2; // 左侧大面板占据2行
        fourthContentPanel.add(largeScrollPane, panelGBC);

        panelGBC.gridx = 1;
        panelGBC.gridy = 0;
        panelGBC.gridheight = 2; // 右侧面板占据3行
        panelGBC.weighty = 0.8;
        fourthContentPanel.add(rightPanels, panelGBC);

        panelGBC.gridx = 0;
        panelGBC.gridy = 2;
        panelGBC.gridwidth = 2; // 按钮面板占据整行
        panelGBC.weighty = 0.2;
        fourthContentPanel.add(buttonPanel2, panelGBC);

        fourthPanel.add(fourthContentPanel, BorderLayout.CENTER);
        rightPanel.add(fourthPanel, gbc);
        return rightPanel;
    }

    public String getUpdateValue(){
        return inputField.getText();
    }

    public void setUpdateValue(String value){
        inputField.setText(value);
    }

    public void setIdentifyAreaValue(String text) {
        identifyArea.setText(text);
    }

    public void addIdentifyButtonListener(ActionListener listener) {
        identifyButton.addActionListener(listener);
    }
    public void addPreviousButtonListener(ActionListener listener) {
        previousButton.addActionListener(listener);
    }
    public void addNextButtonListener(ActionListener listener) {
        nextButton.addActionListener(listener);
    }
    public void addMergeButtonListener(ActionListener listener) {
        mergeButton.addActionListener(listener);
    }
    public void addOkButtonListener(ActionListener listener) {
        okButton.addActionListener(listener);
    }

    public void setRecognizeView(String recognize){
        displayTextArea.setText(recognize);
    }

    public void setMatrixView(WordBean wordBean){
        BufferedImage image = FontUtil.getBufferedImage(wordBean);

//        largeDisplayTextArea.setText(matrix);
        imageDisplayPanel.setImage(image);
    }

    public void setCaptureButtonListener(ActionListener listener) {
        captureButton.addActionListener(listener);
    }

    public int getFontHeight(){
        // 获取文本框内容并进行判空
        String text = fontHeight.getText();
        if (text == null || text.isEmpty()) {
            // 如果文本框为空，则返回默认值或抛出异常
            return 0; // 默认字高为14，或者你可以抛出异常
        }
        try {
            // 尝试将文本转换为整数
            return Integer.parseInt(text);
        } catch (NumberFormatException e) {
            return 14; // 默认字高为14
        }
    }

    public void setRecognizeListener(ActionListener listener){
        recognizeButton.addActionListener(listener);
    }

    public void addColorListValue(ActionListener listener){
        addColorListButton.addActionListener(listener);
    }

    public void deleteColorList(ActionListener listener){
        deleteColorListButton.addActionListener(listener);
    }

    public void setColorListRenderer(LiterateModel model) {
        colorList.setCellRenderer(new ColorItemRenderer(model));
    }

    // 设置颜色列表的交互逻辑
    public void setColorListViewInteraction(MouseAdapter listener){
        colorList.addMouseListener(listener);
    }

    public int getColorListPathViewIndex(MouseEvent e){
        return colorList.locationToIndex(e.getPoint());
    }

    // 设置路径列表的交互逻辑
    public void setFontFilePathViewInteraction(MouseAdapter listener){
        pathList.addMouseListener(listener);
    }

    public int getFontFilePathViewIndex(MouseEvent e){
        return pathList.locationToIndex(e.getPoint());
    }

    public void addFontFilePath(ActionListener listener){
        addFontFilePathButton.addActionListener(listener);
    }

    public void deleteFontFilePath(ActionListener listener){
        deleteFontFileButton.addActionListener(listener);
    }

    public int getFontFilePathSelectIndex(){
        return pathList.getSelectedIndex();
    }

    public void flushFontPathView(List<FontFilePath> fontFilePathList){
        // 删除选中项
        pathListModel.clear();
        for (FontFilePath fontPath: fontFilePathList) {
            pathListModel.addElement(fontPath);
        }
        //刷新
        pathList.repaint();
    }

    public void flushColorListView(List<ColorRecord> colorRecords){
        // 删除选中项
        colorListModel.clear();
        for (ColorRecord colorRecord: colorRecords) {
            colorListModel.addElement(colorRecord);
        }
        //刷新
        colorList.repaint();
    }

    public void setScreenImage(BufferedImage image) {
        int scaledWidth = thumbnailLabel.getWidth();
        int scaledHeight = thumbnailLabel.getHeight();
        Image thumbnail = image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
        thumbnailLabel.setIcon(new ImageIcon(thumbnail));
    }

    public void setSubImage(BufferedImage image) {
        int maxWidth = imageLabel.getWidth() - 20;
        int maxHeight = imageLabel.getHeight() - 20;

        double ratio = (double) image.getWidth() / image.getHeight();
        int scaledWidth = (int) (maxHeight * ratio);
        int scaledHeight = maxHeight;

        if (scaledWidth > maxWidth) {
            scaledWidth = maxWidth;
            scaledHeight = (int) (maxWidth / ratio);
        }

        Image scaledImage = image.getScaledInstance(scaledWidth, scaledHeight, Image.SCALE_SMOOTH);
        imageLabel.setIcon(new ImageIcon(scaledImage));
    }

    //设置下拉框
    public void setSubScreenComboBox(List<LiterateSubScreenBean> subScreenBeans, ActionListener listener){
        for (LiterateSubScreenBean subScreenBean : subScreenBeans) {
            captureComboBox.addItem(subScreenBean.getName());
        }
        captureComboBox.addActionListener(listener);
    }

    // 设置路径、大小和时间显示
    public void setPath(String path) {
        pathValue.setText(path);
    }

    public void setImageSize(String size) {
        sizeValue.setText(size);
    }

    public void setTime(String time) {
        timeValue.setText(time);
    }

    // 获取捕捉框中的字段和选择的选项
    public String[] getCaptureFields() {
        String[] fields = new String[4];
        for (int i = 0; i < 4; i++) {
            fields[i] = captureFields[i].getText();
        }
        return fields;
    }

    public void setCaptureFields(WinDef.RECT rect) {
        captureFields[0].setText(rect.left + "");
        captureFields[1].setText(rect.top + "");
        captureFields[2].setText(rect.right + "");
        captureFields[3].setText(rect.bottom + "");
    }

    public String getSelectedOption() {
        return (String) captureComboBox.getSelectedItem();
    }

    // 截图按钮监听器
    public void addCaptureConfirmButtonListener(ActionListener listener) {
        captureConfirmButton.addActionListener(listener);
    }


    //选图按钮监听
    public void addScreenButtonListener(MouseAdapter adapter) {
        thumbnailLabel.addMouseListener(adapter);
    }

    public void showFileChooserView(LiterateController.FileChooseCallback callback) {
        JFileChooser fileChooser = new JFileChooser();
        fileChooser.setFileFilter(new FileNameExtensionFilter("Image files", "png", "jpg", "txt", "xml"));
        if (fileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
            callback.onFileChoose(fileChooser.getSelectedFile().getAbsolutePath());
        }
    }

    public void showRemarkDialog(LiterateController.FileChooseCallback callback){
        String remark = JOptionPane.showInputDialog(this, "请输入路径备注：", "添加备注", JOptionPane.PLAIN_MESSAGE);
        callback.onFileChoose(remark);
    }

    public void showColorListAddDialog(LiterateController.ColorCallback callback){
        JDialog dialog = new JDialog();
        dialog.setTitle("输入RGB值");
        dialog.setLayout(new GridBagLayout());
        dialog.setModal(true); // 确保对话框是模态的

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.insets = new Insets(5, 5, 5, 5);
        gbc.fill = GridBagConstraints.HORIZONTAL;

        JLabel[] colorLabels = {
                new JLabel("红色 (0-255):"), new JLabel("绿色 (0-255):"),
                new JLabel("蓝色 (0-255):")
        };
        JLabel[] errorLabels = {
                new JLabel("误差±:"), new JLabel("误差±:"), new JLabel("误差±:")
        };
        JTextField[] colorInputFields = new JTextField[3];
        JTextField[] errorInputFields = new JTextField[3];

        for (int i = 0; i < 3; i++) {
            colorInputFields[i] = new JTextField(5);
            errorInputFields[i] = new JTextField(5);

            // 添加颜色标签
            gbc.gridx = 0;
            gbc.gridy = i * 2;
            dialog.add(colorLabels[i], gbc);

            // 添加颜色输入框
            gbc.gridx = 1;
            gbc.gridy = i * 2;
            dialog.add(colorInputFields[i], gbc);

            // 添加误差标签
            gbc.gridx = 2;
            gbc.gridy = i * 2;
            dialog.add(errorLabels[i], gbc);

            // 添加误差输入框
            gbc.gridx = 3;
            gbc.gridy = i * 2;
            dialog.add(errorInputFields[i], gbc);
        }

        JButton confirmButton = new JButton("确认");
        JButton cancelButton = new JButton("取消");

        gbc.gridx = 0;
        gbc.gridy = 6;
        gbc.gridwidth = 4;
        gbc.anchor = GridBagConstraints.CENTER;
        dialog.add(confirmButton, gbc);

        gbc.gridy = 7;
        dialog.add(cancelButton, gbc);

        AtomicReference<Integer[]> resultRef = new AtomicReference<>();

        confirmButton.addActionListener(e -> {
            try {
                Integer[] result = new Integer[6];
                for (int i = 0; i < 3; i++) {
                    String colorText = colorInputFields[i].getText();
                    String errorText = errorInputFields[i].getText();
                    result[i] = Integer.parseInt(colorText);
                    result[i + 3] = Integer.parseInt(errorText);
                    if (result[i] < 0 || result[i] > 255) { // 检查颜色范围
                        throw new NumberFormatException("颜色值超出范围 (0-255)");
                    }
                }
                resultRef.set(result);
                dialog.dispose();
            } catch (NumberFormatException ex) {
                JOptionPane.showMessageDialog(dialog, "请输入0到255之间的整数", "输入错误", JOptionPane.ERROR_MESSAGE);
            }
        });

        cancelButton.addActionListener(e -> {
            resultRef.set(null);
            dialog.dispose();
        });

        dialog.pack();
        dialog.setLocationRelativeTo(null);
        dialog.setVisible(true);
        if (callback != null && resultRef.get() != null) {callback.onColorInput(resultRef.get());}
    }

    public void showJOptionPane(String message) {
        JOptionPane.showMessageDialog(this, message, "错误", JOptionPane.ERROR_MESSAGE);
    }
    public void actionPerformed() {
        // 弹出成功提示对话框
        JOptionPane.showMessageDialog(this, "操作成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
    }

    public void showConfirmDialog(LiterateController.FileChooseCallback callback) {
        int confirm = JOptionPane.showConfirmDialog(this,"确定要删除选中的路径吗？此操作不可恢复！","删除确认",JOptionPane.YES_NO_OPTION,JOptionPane.WARNING_MESSAGE);
        if (confirm == JOptionPane.YES_OPTION) {
            callback.onFileChoose("");
        }
    }
    public static void main(String[] args) {
        // 在事件调度线程中创建并显示 GUI
        SwingUtilities.invokeLater(() -> {
            LiterateView view = new LiterateView();
            view.setVisible(true);
        });
    }
}
